package com.iking.housekeeping.handle;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import com.iking.housekeeping.common.CodeEnum;
import com.iking.housekeeping.common.CommonException;
import com.iking.housekeeping.common.ReturnCode;

/** 
* @author  klaus
* 全局异常处理类，捕获所有来自Controller的异常，打印异常信息到日志文件中，并返回简单错误码给前端。
* @date 创建时间：2017年12月27日 下午12:24:28 
* @version 1.0   
*/
@ControllerAdvice
public class ExceptionHandle {

	private final static Logger logger = LoggerFactory.getLogger(ExceptionHandle.class);

	@ExceptionHandler(value = Exception.class)
	@ResponseBody
	public ReturnCode handle(Exception exception) {
		StackTraceElement stackTraceElement = exception.getStackTrace()[0];
		String exceptionPosition = stackTraceElement.getClassName() + "(" + stackTraceElement.getMethodName() + ":" + stackTraceElement.getLineNumber() + ")";
		if (exception instanceof CommonException) {
			CommonException commonException = (CommonException) exception;
			logger.error(String.format("【" + commonException.getMessage() + "】%s", exceptionPosition));
			return commonException.getReturnCode();
		} else {
			logger.error(String.format("【" + exception.getClass().getSimpleName() + "】%s", exceptionPosition));
			return new ReturnCode(CodeEnum.EXCEPTION);
		}
	}
}
